package com.yeyks.common.utils.apputil;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * AES加密信息
 * @author Administrator
 */
@Slf4j
public class AesEncoder {

    /**
     * 加密用的Key 可以用26个字母和数字组成 此处使用AES-128-CBC加密模式，key需要为16位。
     */
    private String sKey = "yeyukuaisu123456";
    private String ivParameter = "yeyukuaisu123456";
    private static AesEncoder instance = null;

    private AesEncoder() {

    }

    public static AesEncoder getInstance() {
        if (instance == null) {
            instance = new AesEncoder();
        }
        return instance;
    }

    /**
     * 加密 固定 key 和 iv
     * @param sSrc 数据（id）
     * @return
     * @throws Exception
     */
    public String encrypt(String sSrc) throws Exception {
        return convertEncryptSame(sSrc, sKey, ivParameter);
    }

    /**
     *  加密
     * @param encData 数据
     * @param secretKey 密码
     * @param vector 偏移量
     * @return
     * @throws Exception
     */
    public String encrypt(String encData ,String secretKey,String vector) throws Exception {

        if(secretKey == null) {
            return null;
        }
        if(secretKey.length() != 16) {
            return null;
        }
        return convertEncryptSame(encData, secretKey, vector);
    }

    /**
     * 固定的 key 和 iv
     * @param sSrc 数据(id)
     * @return
     */
    public String decrypt(String sSrc) {
        try {
            return convertDecryptSame(sSrc, sKey, ivParameter);
        } catch (Exception ex) {
            return null;
        }
    }

    /**
     * 可以配置的 key 和 iv
     * @param sSrc 数据(id)
     * @param key 密码
     * @param ivs 偏移量
     * @return
     */
    public String decrypt(String sSrc,String key,String ivs) {
        try {
            return convertDecryptSame(sSrc, key, ivs);
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private static String convertEncryptSame(String encData, String secretKey, String vector) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] raw = secretKey.getBytes();
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
        IvParameterSpec iv = new IvParameterSpec(vector.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
        byte[] encrypted = cipher.doFinal(encData.getBytes("utf-8"));
        // 此处使用BASE64做转码。
        return new BASE64Encoder().encode(encrypted);
    }

    private String convertDecryptSame(String sSrc, String sKey, String ivParameter) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, IOException, IllegalBlockSizeException, BadPaddingException {
        byte[] raw = sKey.getBytes("ASCII");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        // 先用base64解密
        byte[] encrypted1 = new BASE64Decoder().decodeBuffer(sSrc);
        byte[] original = cipher.doFinal(encrypted1);
        return new String(original, "utf-8");
    }


    public static String encodeBytes(byte[] bytes) {
        StringBuffer strBuf = new StringBuffer();

        for (int i = 0; i < bytes.length; i++) {
            strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
            strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
        }

        return strBuf.toString();
    }

    public static void main(String[] args) throws Exception {
        // 需要加密的字串
        String cSrc = "1403";

        // 加密
        long lStart = System.currentTimeMillis();
        String enString = AesEncoder.getInstance().encrypt(cSrc);
        System.out.println("加密后的字串是：" + enString);

        long lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("加密耗时：" + lUseTime + "毫秒");
        // 解密
        lStart = System.currentTimeMillis();
        String deString = AesEncoder.getInstance().decrypt(enString);
        System.out.println("解密后的字串是：" + deString);
        lUseTime = System.currentTimeMillis() - lStart;
        System.out.println("解密耗时：" + lUseTime + "毫秒");
    }
}
